/*****************************************************************
 *   Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 ****************************************************************/
package org.epiphron;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.epiphron.ValidityReport.Report;
import org.epiphron.convert.DefaultBeanConverter;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.reasoner.InconsistentOntologyException;
import org.semanticweb.owlapi.reasoner.NodeSet;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;

/**
 * Basic implementation of model validator. 
 * contains most implementation, basically except reasoner creation
 */
public abstract class BasicModelValidator implements ModelValidator {
	
	/**
	 * Creates reasoner object for a given ontology
	 */
	protected abstract OWLReasonerFactory createReasonerFactory(boolean useUNA);

	public Collection<Report> infer(final OWLOntology ontology,
			ConversionMatching matching, boolean useUNA)
			throws InconsistentOntologyException, EpiphronException {

		// array for added reports
		List<Report> reports = new ArrayList<ValidityReport.Report>();

		try {
			OWLOntologyManager manager = ontology.getOWLOntologyManager();
			
			OWLReasonerFactory factory = createReasonerFactory(useUNA);
			OWLReasoner reasoner = factory.createReasoner(ontology);

			for (int i = 0; i < matching.getSize(); i++) {
				OWLNamedIndividual ind = manager.getOWLDataFactory()
						.getOWLNamedIndividual(
								IRI.create(matching.getIndividual(i)
										.toStringID()));

				Map<OWLObjectProperty, Set<OWLNamedIndividual>> rels = getObjectPropertyRelationships(
						reasoner, ind);

				if (!rels.isEmpty()) {
					Class<?> clazz = findClass(ontology, ind);
					if (clazz != null) {
						for (Entry<OWLObjectProperty, Set<OWLNamedIndividual>> entry : rels
								.entrySet()) {
							OWLObjectProperty objProperty = entry.getKey();

							Field field = findField(clazz, ontology,
									entry.getKey());
							if (field != null) {
								field.setAccessible(true);

								List<Object> ranges = new ArrayList<Object>(
										entry.getValue().size());
								for (OWLNamedIndividual individual : entry
										.getValue()) {
									Object bean = toBean(individual, matching);
									if (bean != null) {
										ranges.add(bean);
									}

									manager.addAxiom(
											ontology,
											manager.getOWLDataFactory()
													.getOWLObjectPropertyAssertionAxiom(
															objProperty, ind,
															individual));
								}

								Object value = field.get(matching.getBean(i));
								if (value instanceof Collection<?>) {
									@SuppressWarnings("unchecked")
									Collection<Object> collection = (Collection<Object>) value;

									// adding all inferred
									for (Object range : ranges) {
										if (!collection.contains(range)) {
											collection.add(range);

											// adding a report
											reports.add(new Report(
													ReportType.INFER, matching
															.getBean(i), range,
													"Object added to subject's collection "
															+ field.getName()));
										}
									}
								}
							}
						}
					}
				}
			}

			return reports;

		} catch (InconsistentOntologyException e) {
			// rethrow. inferring cannot be done, the ontology is too
			// inconsistent
			throw e;
		} catch (Exception e) {
			throw new EpiphronException("Cannot infer", e);
		}
	}

	private Map<OWLObjectProperty, Set<OWLNamedIndividual>> getObjectPropertyRelationships(
			OWLReasoner reasoner, OWLNamedIndividual individual) {
		Map<OWLObjectProperty, Set<OWLNamedIndividual>> values = new HashMap<OWLObjectProperty, Set<OWLNamedIndividual>>();
		Set<OWLObjectProperty> objProps = reasoner.getRootOntology()
				.getObjectPropertiesInSignature();
		for (OWLObjectProperty prop : objProps) {
			NodeSet<OWLNamedIndividual> set = reasoner.getObjectPropertyValues(
					individual, prop);
			if (!set.isEmpty()) {
				values.put(prop, set.getFlattened());
			}

		}

		return values;
	}
	
	public ValidityReport validate(OWLOntology ontology, boolean useUNA)
			throws EpiphronException {
		OWLReasonerFactory factory = createReasonerFactory(useUNA);
		OWLReasoner reasoner = factory.createReasoner(ontology);

		SimpleValidityReport report = new SimpleValidityReport();

		if (!reasoner.isConsistent()) {
			String[] explanations = getExplanations(ontology, factory, reasoner);
			
			for (String explanation : explanations) {
				report.addReport(new Report(ReportType.ERROR, explanation));
			}
		}

		return report;
	}

	/**
	 * Returns all found explanations for inconsistent ontology
	 */
	protected abstract String[] getExplanations(OWLOntology ontology,
			OWLReasonerFactory factory, OWLReasoner reasoner);

	/**
	 * Finds Java field for specified object property, following Jenabean
	 * annotations
	 */
	private Field findField(Class<?> clazz, OWLOntology ontology,
			OWLObjectProperty property) {
		Set<OWLAnnotation> annotations = property.getAnnotations(ontology);
		for (OWLAnnotation annotation : annotations) {
			if (DefaultBeanConverter.JAVAFIELD.equals(annotation.getProperty()
					.getIRI().toString())) {
				while (clazz != Object.class) {
					String fieldName = ((OWLLiteral) annotation.getValue())
							.getLiteral();
					try {
						return clazz.getDeclaredField(fieldName);
					} catch (Exception e) {
						// cannot read. just skip for now
					}
					clazz = clazz.getSuperclass();
				}
			}

		}

		return null;
	}

	/**
	 * Finds Java class for specified individual, following Jenabean annotations
	 */
	private Class<?> findClass(OWLOntology ontology, OWLNamedIndividual ind)
			throws ClassNotFoundException {
		Set<OWLClassAssertionAxiom> classes = ontology
				.getClassAssertionAxioms(ind);

		for (OWLClassAssertionAxiom owlClassAxiom : classes) {
			OWLClassExpression expr = owlClassAxiom.getClassExpression();

			if (!expr.isAnonymous()) {
				Set<OWLAnnotation> annotations = expr.asOWLClass()
						.getAnnotations(ontology);
				for (OWLAnnotation annotation : annotations) {
					if (DefaultBeanConverter.JAVACLASS.equals(annotation
							.getProperty().getIRI().toString())) {
						String className = ((OWLLiteral) annotation.getValue())
								.getLiteral();

						return Thread.currentThread().getContextClassLoader()
								.loadClass(className);
					}

				}
			}
		}
		return null;
	}

	/**
	 * Converts specified named individual to Java Beans Supports lookup in
	 * known bean-individual pair array
	 * 
	 * @param individual
	 * @param beans
	 * @param individuals
	 * @return
	 */
	private Object toBean(OWLNamedIndividual individual,
			ConversionMatching matching) {
		String uri = individual.getIRI().toString();
		for (int i = 0; i < matching.getSize(); i++) {
			if (matching.getIndividual(i).toStringID().equals(uri)) {
				return matching.getBean(i);
			}
		}

		// TODO: add conversion
		return null;
	}

}
